package jaoso.framework.security.impl;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;

/**
 * A simple CallbackHandler that handles name and password
 * 
 * 
 * @author Charles Huang
 * @since JDK1.4
 * @version $Id: SimpleCallbackHandler.java,v 1.1.1.1 2004/02/04 03:52:13
 *          mustang Exp $
 */
public class SimpleCallbackHandler implements CallbackHandler
{
    /** DOCUMENT ME! */
    private String password;

    /** DOCUMENT ME! */
    private String username;

    /**
     * Creates a new SimpleCallbackHandler object.
     * 
     * @param arg0
     *            DOCUMENT ME!
     * @param arg1
     *            DOCUMENT ME!
     */
    public SimpleCallbackHandler(final String arg0, final String arg1)
    {
        this.username = arg0;
        this.password = arg1;
    }

    /**
     * This handler only hanldes name and password
     * 
     * @param callbacks
     *            an array of <code>Callback</code> objects provided by an
     *            underlying security service which contains the information
     *            requested to be retrieved or displayed.
     * 
     * @exception java.io.IOException
     *                if an input or output error occurs.
     *                <p>
     * @exception UnsupportedCallbackException
     *                if the implementation of this method does not support one
     *                or more of the Callbacks specified in the
     *                <code>callbacks</code> parameter.
     */
    public final void handle(final Callback[] callbacks) throws IOException,
            UnsupportedCallbackException
    {
        for (int index = 0; index < callbacks.length; index++)
        {
            if (callbacks[index] instanceof NameCallback)
            {
                NameCallback ncb = (NameCallback) callbacks[index];
                ncb.setName(username);
            }

            if (callbacks[index] instanceof PasswordCallback)
            {
                PasswordCallback pcb = (PasswordCallback) callbacks[index];
                pcb.setPassword(password.toCharArray());
            }
        }
    }
}